//文章相关接口
const express = require('express');
const router = express.Router();

const db = require('../db');

const multer  = require('multer');
const upload = multer({ dest: 'uploads/' });

const moment = require('moment');

// ---------------- 分页获取文章列表 ----------------
// 接口要求：
/**
 * 请求方式：GET
 * 请求的url：/my/article/list
 * 请求参数：
 *  - pagenum -- 页码值
 *  - pagesize -- 每页显示多少条数据
 *  - cate_id -- 文章分类的Id
 *  - state -- 文章的状态，可选“草稿”或“已发布”
 */
 router.get('/list', (req, res) => {
  // console.log(req.query);
  // 设置变量，接收请求参数
  let { pagenum, pagesize, cate_id, state } = req.query;
  // console.log(cate_id, state);
  // 根据cate_id 和 state制作SQL语句的条件
  let w = '';
  if (cate_id) {
    w += ` and cate_id=${cate_id} `;
  }

  if (state) {
    w += ` and state='${state}' `;
  }
  // 分页查询数据的SQL（该SQL用到了连表查询，并且使用了很多变量组合）
  let sql1 = `select a.id, a.title, a.state, a.pub_date, c.name cate_name from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}
    limit ${(pagenum - 1) * pagesize}, ${pagesize}`;
  // 查询总记录数的SQL，查询条件和前面查询数据的条件 必须要一致
  let sql2 = `select count(*) total from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}`;
  // 分别执行两条SQL（因为db查询数据库是异步方法，必须嵌套查询）
  db(sql1, (err, result1) => {
    if (err) throw err;
    db(sql2, (e, result2) => {
      if (e) throw e;
      res.send({
        status: 0,
        message: '获取文章列表数据成功',
        data: result1,
        total: result2[0].total
      });
    })
  })
});


//添加文章
router.post('/add', upload.single('cover_img'), (req, res) => {
  //upload.single('cover_img') cover_img图片这个字段的名称
  //console.log(req.body);//{title: 'sdsd',cate_id: '1',state: '已发布',content: 'fdsfdfffffffffffffffffffffffffff'}
  //console.log(req.file);//  {...filename: '005fc57da31953e4ed739089530da6bc',path: 'uploads\\005fc57da31953e4ed739089530da6bc',size: 10102}
  const {title, cate_id, state, content} = req.body;
  let pub_date = moment().format('YYYY-MM-DD HH:mm:ss');
  const sql = `insert into article set title='${title}', content='${content}', cover_img='${req.file.filename}', cate_id=${cate_id}, author_id=${req.user.id}, state='${state}', pub_date='${pub_date}', is_delete=0`
  db(sql, (err, result) => {
    if(err) throw err;
    res.send({status: 0, message: '添加文章成功'});
  })
})


//删除文章
router.get('/delete/:id', (req, res) => {
  db(`update article set is_delete=1 where is_delete=0 and id=${req.params.id} and author_id=${req.user.id}`, (err, result) => {
    if(err) throw err;
    if(result.affectedRows > 0) {
      res.send({status: 0, message: '删除成功'});
    }else {
      res.send({status: 1, message: '删除失败'});
    }
  })
});

module.exports = router;